﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Users
{
    public partial class UsersControl : UserControl
    {
        private readonly Business.Business _business;

        public UsersControl()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void UsersControlLoad(object sender, EventArgs e)
        {
            LoadUser();
            Dock = DockStyle.Top;
        }

        private void LoadUser()
        {
            dgvUsers.DataSource = _business.GetListUser();

            DataGridViewHelper.ShowHideColumns(dgvUsers, new[] { "IsChecked", "Name", "PermissionName" });//, "Password" 
            DataGridViewHelper.ShowIsCheck(dgvUsers);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvUsers, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvUsers, new[] { "IsChecked", "Name", "PermissionName" },
                                                   new[] { "Chọn", "Tên đăng nhập", "Quyền hạn" }); //, "Password" 

            UserCurrentRowChanged();
        }

        private void UserCurrentRowChanged()
        {
            if (dgvUsers.CurrentRow != null)
            {
                txtUser.Text = dgvUsers.CurrentRow.Cells["Name"].Value.ToString();
                txtPass.Text = dgvUsers.CurrentRow.Cells["Password"].Value.ToString();
                cboPermission.SelectedIndex = (int)dgvUsers.CurrentRow.Cells["Permission"].Value;
                //switch (permission)
                //{
                //    case 0:
                //        cboPermission.Text = @"Admin";
                //        break;
                //    case 1:
                //        cboPermission.Text = @"Trưởng khoa";
                //        break;
                //    case 2:
                //        cboPermission.Text = @"Trợ lý đào tạo";
                //        break;
                //    default:
                //        cboPermission.Text = @"Khách";
                //        break;
                //}
            }
            else
                txtUser.Text = txtPass.Text = string.Empty;
        }

        private void DgvUsersCurrentCellChanged(object sender, EventArgs e)
        {
            UserCurrentRowChanged();
        }

        private void DgvUsersCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvUsers == null ||
               dgvUsers.Columns[(string)typeof(User).Properties().IsChecked] == null ||
               dgvUsers.Columns[(string)typeof(User).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvUsers[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvUsers[e.ColumnIndex, e.RowIndex].Value;

            ckbAllUser.Checked = DataGridViewHelper.AllRowsIsCheck(dgvUsers);
        }

        private void CkbAllUsersCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvUsers, ckbAllUser.Checked);
        }

        private void ReloadUser(User user)
        {
            LoadUser();
            DataGridViewHelper.SetDgvCurrentCell(dgvUsers, user.Name);
            UserCurrentRowChanged();
        }

        /// <summary>
        /// Event click button Add User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddUserClick(object sender, EventArgs e)
        {
            try
            {
                var user = new User
                {
                    Name = txtUser.Text.Trim(),
                    Password = txtPass.Text.Trim(),
                    Permission = cboPermission.SelectedIndex
                };

                string message;

                if (_business.AddUserValidator(user, out message))
                {
                    _business.AddUser(user);

                    ReloadUser(user);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click edit User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditUserClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvUsers.CurrentRow != null)
                {
                    var user = new User
                    {
                        Id = Convert.ToInt32(dgvUsers.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        Name = txtUser.Text.Trim(),
                        Password = txtPass.Text.Trim(),
                        Permission = cboPermission.SelectedIndex
                    };
                    string message;
                    if (_business.EditUserValidator(user, out message))
                    {
                        if (!_business.EditUser(user))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadUser(user);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteUserClick(object sender, EventArgs e)
        {
            try
            {
                var users = new List<User>();
                string message;

                for (var i = 0; i < dgvUsers.RowCount; i++)
                {
                    if (!(bool)dgvUsers[(string)typeof(User).Properties().IsChecked, i].Value) continue;

                    users.Add(new User
                                  {
                                      Id = (int)dgvUsers[(string)typeof(User).Properties().Id, i].Value,
                                      Name = dgvUsers[(string)typeof(User).Properties().Name, i].Value.ToString(),
                                      Password = dgvUsers["Password", i].Value.ToString(),
                                      Permission = cboPermission.SelectedIndex
                                  });
                }
                if (users.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteUsersValidator(users, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các người dùng đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteUsers(users);
                        ReloadUser(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void PicSearchUserClick(object sender, EventArgs e)
        {
            Search();
        }

        private void Search()
        {
            var keyName = txtUserSearch.Text.Trim();

            if (string.IsNullOrEmpty(keyName))
                dgvUsers.DataSource = _business.GetListUser();

            dgvUsers.DataSource = _business.GetListUserByKeyword(keyName);

            UserCurrentRowChanged();
        }

        private void txtUserSearch_TextChanged(object sender, EventArgs e)
        {
            Search();
        }
    }
}
